package common

import (
	"crypto/tls"
	"crypto/x509"
	"encoding/base64"
)

// TlsCfg 解析base64编码的证书和密钥，生成tls配置
func TlsCfg(caB64, certB64, keyB64 string, isServer bool) (*tls.Config, error) {
	caBytes, err := base64.StdEncoding.DecodeString(caB64)
	if err != nil {
		return nil, err
	}
	caPool := x509.NewCertPool()
	caPool.AppendCertsFromPEM(caBytes)

	certBytes, err := base64.StdEncoding.DecodeString(certB64)
	if err != nil {
		return nil, err
	}
	keyBytes, err := base64.RawStdEncoding.DecodeString(keyB64)
	if err != nil {
		return nil, err
	}
	tlsPair, err := tls.X509KeyPair(certBytes, keyBytes)
	if err != nil {
		return nil, err
	}
	result := &tls.Config{
		Certificates: []tls.Certificate{tlsPair},
	}

	if isServer {
		// 是服务端
		result.ClientAuth = tls.RequireAndVerifyClientCert
		result.ClientCAs = caPool
	} else {
		// 是客户端
		result.InsecureSkipVerify = true
		result.RootCAs = caPool
	}
	return result, nil
}
